package controller;


import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import exciptions.DublicatedUserExcitpion;
import exciptions.InvalidPasswordtException;

import model.User;
import model.UsersManager;

/**
 * Servlet implementation class RegisterServlet
 */
@WebServlet("/RegisterServlet")
public class RegisterServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public RegisterServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		String login = request.getParameter("login");
		String pass = request.getParameter("password");
		String name = request.getParameter("name");
		String email = request.getParameter("email");
		PrintWriter printWriter = response.getWriter();

		
		
		ServletContext con = getServletContext();
		UsersManager users = (UsersManager) con.getAttribute("users");
		
		
		User user = new User(login);
		user.setEmail(email);
		user.setName(name);
		
		try {
			
			user.setPassword(pass);
			users.addUser(user);
			users.writeXML();
			con.setAttribute("users", users);
			printWriter.println("<h1>Registeration completed</h1>");
			request.setAttribute("user", user);
			request.getRequestDispatcher("welcome.jsp").include(request, response);
		} catch (DublicatedUserExcitpion e) {
			printWriter.println(e.getMessage());
			request.setAttribute("user", user);
			request.getRequestDispatcher("register.jsp").include(request, response);
		} catch (InvalidPasswordtException e) {
			printWriter.println(e.getMessage());
			request.setAttribute("user", user);
			request.getRequestDispatcher("register.jsp").include(request, response);
		}
		
		
		
	}

}
